console.inspectEnable = true;
import dns from 'edgeros:dns';
import LightKV from 'lightkv';

const sceneDB = new LightKV('scene.lkv', 'c+', LightKV.OBJECT);

/**
 * {
 *     devs: [
 *        {
 *          devid: string,
 *          settings: {
 *            alarm_value: number,  // 气体警告值
 *            window_percent: number // 窗户位置
 *          }
 *        }
 *      ]
 * }
 */
const obj: { devs: Array<{ devid: string; settings: { alarm_value?: number; window_percent?: number } }> } =
  Object.fromEntries(sceneDB.toMap() as Array<any>) as any;
console.info('[cam db]:', obj);

// 数据库set仅可通过一级 = 赋值
// 一级属性
const db = new Proxy(obj, {
  get: (target, key, receiver): string[] => {
    return Reflect.get(target, key, receiver) || [];
  },

  set: (target, key, value, receiver) => {
    try {
      updateDB(key, value);
      return Reflect.set(target, key, value, receiver);
    } catch (error) {
      console.error('Failed to modify database');
      throw error;
    }
  }
});

initDB();

function initDB() {
  if (!db.devs) {
    db.devs = [];
  }
}

function updateDB(key, value) {
  try {
    sceneDB.begin();
    sceneDB.set(key, value);
    sceneDB.commit();
  } catch (error) {
    sceneDB.rollback();
    throw new Error('修改数据库失败！');
  }
}

console.log('gas_window Database:', JSON.stringify(db, undefined, 2));

export default db;
